/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package teacher;

import common.MessageModel;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Eugene-Forest
 */
public class SaveHistoryThread extends Thread {

    private MessageModel messageModel;
    private Date publishDate;

    public SaveHistoryThread(MessageModel messageModel, Date publishDate) {
        this.messageModel = messageModel;
        this.publishDate = publishDate;
    }

    @Override
    public void run() {
        //将失去实时性的公告添加入共享数据中心以作为一个缓存
        messageModel.setReal_time(false);
        DataCenter.add_messageModel(new MessageModel(messageModel));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String publishTime = dateFormat.format(publishDate);
        makeDir("c:/red_spider/");
        makeDir("c:/red_spider/history/");
        String name = "c:/red_spider/history/" + publishTime + ".txt";
        File file = new File(name);
        //处理信息文本
        if (messageModel.getMessageString().contains("\n")) {
            String[] infoStrings = messageModel.getMessageString().split("\\n");
            String resultString = "";
            for (int i = 0; i < infoStrings.length; i++) {
                if (i != infoStrings.length - 1) {
                    resultString += infoStrings[i] + "<|@Enter@|>";
                } else {
                    resultString += infoStrings[i];
                }
            }
            messageModel.setMessageString(resultString);
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
            String message = messageModel.getPublishDate() + "<|@Cut@|>" + messageModel.getMessageString()
                    + "<|@Cut@|>" + messageModel.getType().toString() + "<|@Cut@|>" + messageModel.isReal_time() + "\r\n";
            System.out.println(message);
            bos.write(message.getBytes());
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void makeDir(String path){
        File dir = new File(path);
        //如果文件夹不存在则创建
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdir();
        }
    }
}
